import time, os, redis
from selenium.webdriver.common.by import By

import config
from tools import web_find_element, web_find_elements
from ding_api import get_access_token, upload_attendance_record


def login(bro, url):
    """模拟登录"""
    bro.get(url)
    login_username = bro.find_element(By.ID, "username")
    login_username.send_keys(config.USER_NAME)
    login_password = bro.find_element(By.ID, "password")
    login_password.send_keys(config.PASS_WORD)
    login_button = bro.find_element(By.CLASS_NAME, 'login-btn')
    login_button.click()


def get_view_data(bro, data, equipment, next=None):
    """递归调用进行查询下一页"""    
    # 获取查询结果
    web_data = web_find_elements(bro, '//*[@id="main"]/div[2]/div/div[2]/div/table/tbody/tr')

    if not web_data:
        return None
        
    # 将数据清洗
    for item in web_data:
        row = (item.text).split(" ") or []
        row += [equipment['name'], equipment['id']]
        if row[0] in config.user_dict:
            row.append(config.user_dict[row[0]]['ding_id'])
            data.append(row)           

    # 检查是否还有下一页
    next_page = web_find_element(bro, '//*[@id="main"]/div[2]/div/div[2]/div/table/tfoot/tr/td/div/ul/li[last()]')
    next = next_page.get_attribute('class')

    if next == 'disabled':
        return data

    # 有下一页，点击下一页
    next_page_span = web_find_element(bro, '//*[@id="main"]/div[2]/div/div[2]/div/table/tfoot/tr/td/div/ul/li[last()]/span')
    next_page_span.click()

    # 递归调用自己
    get_view_data(bro, data, equipment, next) 


def ding_upload(token, data):
    """上传考勤机数据"""
    # 1.读取redis缓存，避免重复上传
    r = dict()
    try:
        pool = redis.ConnectionPool(host='172.16.11.8', port=6379, decode_responses=True)
        r = redis.Redis(connection_pool=pool)
    except Exception:
        r = dict()

    # 2.获取钉钉access_token
    if not isinstance(token, dict) or (token.get('expires') < time.time()):
        ding_access_toke = get_access_token()
        token['access_token'] = ding_access_toke.get('access_token') or None
        token['expires'] = time.time() * 1000 + ding_access_toke.get('expires_in') - 60 or None

    # 判断并打开日志文件
    log_file = str(time.strftime("%Y-%m")) + '.txt'
    m = 'a' if os.path.exists(log_file) else 'w'
    f_obj = open(file=log_file, mode=m)

    
    for item in data:
        access_token = token.get('access_token')
        user_id = item[-1] 
        device_name = item[-3] 
        device_id = item[-2]
        date_time = item[3] + ' ' + item[4] 
        user_check_time = int(time.mktime(time.strptime(date_time, "%Y-%m-%d %H:%M:%S"))) * 1000        
                
        # 3.判断获取数据是否存在缓存，避免重复上传
        key = config.DING_REDIS_PREFIX + user_id + str(user_check_time)         
        if r.get(key):
            print('redis_key:', key, r.get(key))
            continue

        rel = upload_attendance_record(access_token, user_id, device_name, device_id, user_check_time)
        ding_rel = ''

        if isinstance(rel, str):
            ding_rel = '更新失败'+rel
            

        elif isinstance(rel, dict) and rel.get('errcode') == 0:
            ding_rel = '更新成功'
            try:
                r.set(key, user_check_time, ex=86400)  # 设置 name 对应的值
            except Exception:
                pass
        else:
            ding_rel = '更新失败'+str(rel.get('errcode'))

        now_time = time.strftime("%Y-%m-%d %H:%M:%S")
        count = '%s %s %s %s \n' % (now_time, user_id, user_check_time, ding_rel)
        print(rel, count)
        f_obj.write(count)
        f_obj.flush()#强制刷新  

    f_obj.close()


def is_expired(token):
    """判断token是否过期"""
    now_time = time.time() * 1000
    if not token.get('expires'):
        return False
    if now_time > float(token.get('expires')):
        return True
    return False